package com.shadow.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class TimerFilter implements Filter {
    private static final Logger logger = LoggerFactory
            .getLogger(TimerFilter.class);
    public static final String TIMER_BEGIN = "_timerBegin";
    public static final NumberFormat FORMAT = new DecimalFormat("0.000");

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        long begin = System.currentTimeMillis();

        try {
            chain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            //((HttpServletResponse) response).sendRedirect("/index.do");
        }

        if (logger.isInfoEnabled()) {
            long end = System.currentTimeMillis();
            BigDecimal processed = new BigDecimal(end - begin)
                    .divide(new BigDecimal(1000));
            String uri = ((HttpServletRequest) request).getRequestURI();
            logger.info("Processed in {} second(s). URI={}",
                    FORMAT.format(processed), uri);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}